#include "GraficaEditor.h"
#include <stdio.h>
#include <string.h>

GraficaEditor::GraficaEditor(int argc, char *argv[],Campo * c){

  /*Inicializa la libreraia*/   	
  gtk_init (&argc, &argv);
  
  /*Inicializa la matriz del campo*/	
  for(int i=0;i<20;i++)
	 for(int j=0;j<15;j++)
		 campo[i][j]=0;
	 
   tipoDeCultivo=0;	 
   pixmap=NULL;
	ventana=NULL;	 
   seGuardoCambios=false;	 
	 
  /*Crea la ventana*/
  window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
  gtk_window_set_title (GTK_WINDOW (window), "Editor");	
  gtk_window_set_default_size(GTK_WINDOW(window),840,540);
  gtk_container_set_border_width (GTK_CONTAINER (window), 10);
  
	 
  /*Funcion  que se llama al cerrar la ventana*/	
  gtk_signal_connect (GTK_OBJECT (window), "destroy", (GtkSignalFunc)gtk_main_quit , NULL);  
   gtk_signal_connect (GTK_OBJECT (window), "delete_event", (GtkSignalFunc)callback_delete_event , this);  
  
   /*Crea Contenedor horizontal*/
  hbox = gtk_hbox_new (FALSE, 0);
  gtk_container_add (GTK_CONTAINER (window), hbox);
  gtk_widget_show (hbox);
   /*Crea Contenedor verical*/
  vbox = gtk_vbox_new (FALSE, 0);
  gtk_container_add (GTK_CONTAINER (hbox), vbox);
  gtk_widget_show (vbox);	 

 /*Crea frame del Campo*/
 frameCampo=gtk_frame_new( "Campo"); 
 gtk_box_pack_start (GTK_BOX (hbox), frameCampo, TRUE, TRUE, 10);
 gtk_frame_set_shadow_type( GTK_FRAME(frameCampo), GTK_SHADOW_ETCHED_OUT);
 gtk_widget_show(frameCampo);



 /* Crear la zona de dibujado */
  drawing_area = gtk_drawing_area_new ();
  gtk_drawing_area_size (GTK_DRAWING_AREA (drawing_area), 32*20, 15*32);
  gtk_container_add (GTK_CONTAINER (frameCampo), drawing_area);
 gtk_widget_show (drawing_area); 
 
 /*Crea el frame de las herramientas*/
gtk_box_pack_start (GTK_BOX (vbox), creaFrameArchivos(), TRUE, TRUE, 10);
gtk_box_pack_start (GTK_BOX (vbox), creaCajaBotones(), TRUE, TRUE, 10);


 setCallbacks(); 
 gtk_widget_show (window);
 
 gtk_main ();	


}

void GraficaEditor:: setCallbacks(){

/* Las señales utilizadas para manejar el backing pixmap */
  gtk_signal_connect (GTK_OBJECT (drawing_area), "expose_event",
                      (GtkSignalFunc) callback_expose_event,  this );
 gtk_signal_connect (GTK_OBJECT(drawing_area),"configure_event",
                      (GtkSignalFunc) callback_configure_event, this);            

  /* Señales evento */

  gtk_signal_connect (GTK_OBJECT (drawing_area), "motion_notify_event",
                      (GtkSignalFunc) callback_motion_notify_event, this);
  gtk_signal_connect (GTK_OBJECT (drawing_area), "button_press_event",
                      (GtkSignalFunc)callback_button_press_event, this);

  gtk_widget_set_events (drawing_area, GDK_EXPOSURE_MASK
                         | GDK_LEAVE_NOTIFY_MASK
                         | GDK_BUTTON_PRESS_MASK
                         | GDK_POINTER_MOTION_MASK
                         | GDK_POINTER_MOTION_HINT_MASK);

 
}

GtkWidget * GraficaEditor::creaCajaBotones(){
	
	
  GtkWidget *frame;
  GtkWidget *bbox;
  GtkWidget *boton;

  /*Crea un frame*/
  frame = gtk_frame_new ("Cultivos");
 /*Crea contenedor de botones*/
  bbox = gtk_vbutton_box_new ();
  
  
  gtk_container_set_border_width (GTK_CONTAINER (bbox), 5);
  gtk_container_add (GTK_CONTAINER (frame), bbox);

  /* Establece la apariencia de la Caja de Botones */
  gtk_button_box_set_layout (GTK_BUTTON_BOX (bbox),GTK_BUTTONBOX_SPREAD);
  gtk_button_box_set_spacing (GTK_BUTTON_BOX (bbox), 0);
  
   boton = gtk_button_new_with_label ("Inexistente");
  gtk_container_add (GTK_CONTAINER (bbox), boton);
   /*Accion del boton al clickear*/
  gtk_signal_connect (GTK_OBJECT (boton), "clicked", (GtkSignalFunc) (apretarBotonInexistente),this);		 
  boton = gtk_button_new_with_label ("Sin plantar");
  gtk_container_add (GTK_CONTAINER (bbox), boton);
   /*Accion del boton al clickear*/
  gtk_signal_connect (GTK_OBJECT (boton), "clicked", (GtkSignalFunc) (apretarBotonSinPlantar),this);		 
	
  boton = gtk_button_new_with_label ("Maiz");
  gtk_container_add (GTK_CONTAINER (bbox), boton);
   /*Accion del boton al clickear*/
  gtk_signal_connect (GTK_OBJECT (boton), "clicked", (GtkSignalFunc) (apretarBotonMaiz),this);	
      
  boton = gtk_button_new_with_label ("Girasol");
  gtk_container_add (GTK_CONTAINER (bbox), boton);
   /*Accion del boton al clickear*/
  gtk_signal_connect (GTK_OBJECT (boton), "clicked", (GtkSignalFunc) (apretarBotonGirasol),this);	
  
   boton = gtk_button_new_with_label ("Soja");
   gtk_container_add (GTK_CONTAINER (bbox), boton);
   /*Accion del boton al clickear*/
  gtk_signal_connect (GTK_OBJECT (boton), "clicked",  (GtkSignalFunc) (apretarBotonSoja),this);	
  
  gtk_widget_show_all (frame);
  return(frame);

}

GtkWidget * GraficaEditor::creaFrameArchivos (){
	
	GtkWidget *frame;
    GtkWidget *bbox;
    GtkWidget *boton;

  /*Crea un frame*/
  frame = gtk_frame_new ("Archivos");
 /*Crea contenedor de botones*/
  bbox = gtk_vbutton_box_new ();
  gtk_container_set_border_width (GTK_CONTAINER (bbox), 5);
  gtk_container_add (GTK_CONTAINER (frame), bbox);

  /* Establece la apariencia de la Caja de Botones */
  gtk_button_box_set_layout (GTK_BUTTON_BOX (bbox),GTK_BUTTONBOX_SPREAD);
  gtk_button_box_set_spacing (GTK_BUTTON_BOX (bbox), 0);
  
  
  boton = gtk_button_new_with_label ("Abrir");
  gtk_container_add (GTK_CONTAINER (bbox), boton);
   /*Accion del boton al clickear*/
  gtk_signal_connect (GTK_OBJECT (boton), "clicked", (GtkSignalFunc) (apretarBotonAbrir),this);		 
	 boton = gtk_button_new_with_label ("Guardar");
  gtk_container_add (GTK_CONTAINER (bbox), boton);
   /*Accion del boton al clickear*/
  gtk_signal_connect (GTK_OBJECT (boton), "clicked", (GtkSignalFunc) (apretarBotonGuardar),this);		 
  
   boton = gtk_button_new_with_label ("Salir");
   gtk_container_add (GTK_CONTAINER (bbox), boton);
   /*Accion del boton al clickear*/
  gtk_signal_connect (GTK_OBJECT (boton), "clicked", (GtkSignalFunc) (callback_cerrarVentana),this);		 
	 gtk_widget_show_all (frame);
	return frame;
}


void GraficaEditor:: dibujaCampo(GtkWidget *widget){
  
  /*Punto de inicio*/
  gint i=10;
 /*gint j=10; */
 dibujarParcelas(widget);
 gdk_draw_line (pixmap,widget->style->black_gc,10,10,10,490); /*v izquierda*/
 gdk_draw_line (pixmap,widget->style->black_gc,10,10,650,10); /*H arriba*/
 gdk_draw_line (pixmap,widget->style->black_gc,10,490,650,490); /*H abajo*/
 gdk_draw_line (pixmap,widget->style->black_gc,650,10,650,490); /*v derecha*/
 
/*Lineas verticales*/
 for(i=0;i<20;i++)
    gdk_draw_line (pixmap,widget->style->black_gc,10+i*32,10,10+i*32,490);	
 /*Lineas horizontales*/
  for(i=0;i<15;i++)
     gdk_draw_line (pixmap,widget->style->black_gc,10,10+i*32,650,10+i*32); 	
  
}


/* Redibujamos la pantalla con el backing pixmap */
gboolean GraficaEditor::expose_event (GtkWidget *widget, GdkEventExpose *event){
    
	gdk_draw_pixmap(widget->window,
                  widget->style->fg_gc[GTK_WIDGET_STATE (widget)],
                  pixmap,
                  event->area.x, event->area.y,
                  event->area.x, event->area.y,
                  event->area.width, event->area.height);

  return FALSE;
 
}


/* Dibujamos un rectángulo en la pantalla */
void GraficaEditor::draw_brush (GtkWidget *widget, gdouble x, gdouble y)
{
   
	int coorX= (int) ( (x-10)/32 );
	int coorY= (int)  ((y-10)/32);
	
	GdkRectangle update_rect;
	update_rect.x = 10+coorX*32;
    update_rect.y = 10+coorY*32;
    update_rect.width = 32;
    update_rect.height = 32;
	
	campo[coorX][coorY]=tipoDeCultivo;
	dibujaCampo(widget);	
	gtk_widget_draw (widget, &update_rect);
}

void GraficaEditor::dibujarParcelas(GtkWidget *widget){
	
	GdkGC*  gc;
  
		   for(int i=0;i<20;i++)
			   for(int j=0;j<15;j++){
		    /*Parcela vacia  BLANCA*/
			if(campo[i][j]==0)
				gc=setColor(widget,255,255,255);	
			/*Sin plantar Marron*/
	        if(campo[i][j]==1)
		        gc=setColor(widget,120,120,0);	
			/*Maiz  Amarillo*/
	        if(campo[i][j]==2)
		         gc=setColor(widget,255,255,0);	
			/*Girasol naranja*/
	        if(campo[i][j]==3)
		         gc=setColor(widget,255,160,0);	
			/*Soja Rojo*/
	        if(campo[i][j]==4)
		         gc=setColor(widget,255,0,0);	
			
	       gdk_draw_rectangle(pixmap, gc, 1,10+i*32,10+j*32 ,32 , 32);
		}	
}
gboolean GraficaEditor:: button_press_event (GtkWidget *widget, GdkEventButton *event)
{ 

 if (event->button == 1 && pixmap != NULL ){
	
    draw_brush (widget, event->x, event->y);
	   
  }
  dibujaCampo(widget);	
  return TRUE;
}

gboolean GraficaEditor:: motion_notify_event (GtkWidget *widget, GdkEventMotion *event)
{
  int x, y;
  GdkModifierType state;
 
	if (event->is_hint)
    gdk_window_get_pointer (event->window, &x, &y, &state);
  else
    {
      x = (int)event->x;
      y = (int)event->y;
      state = (GdkModifierType)event->state;
    }
    
  if (state & GDK_BUTTON1_MASK && pixmap != NULL ){
    draw_brush (widget, x, y);
  }
     return TRUE;
}

gboolean GraficaEditor::configure_event (GtkWidget *widget, GdkEventConfigure *event)
{
  if (pixmap)
    gdk_pixmap_unref(pixmap);

   pixmap = gdk_pixmap_new(widget->window,
                          widget->allocation.width,
                          widget->allocation.height,
                          -1);
  gdk_draw_rectangle (pixmap,
                      widget->style->white_gc,
                      TRUE,
                      0, 0,
                      widget->allocation.width,
                      widget->allocation.height);
  
  dibujaCampo(widget);
  return TRUE;
}

void GraficaEditor::quit () {  
	gtk_exit (0); }


GdkGC*  GraficaEditor:: setColor(GtkWidget* widget,int red, int green, int blue){
	
  GdkColor color;
  GdkGC *gc;
  
  /* Crea un contexto grafico */
  gc = gdk_gc_new(widget->window);
 
  /*Setea lo valore RGB del color*/ 
   color.red = red * (65535/255);
   color.green = green*(65535/255);
   color.blue = blue*(65535/255);
   /*Aloca el color*/
   gdk_colormap_alloc_color(gtk_widget_get_colormap(widget),&color, TRUE,TRUE);
   gdk_gc_set_foreground(gc, &color);
   return gc;
  
}

/*Cambia las herramientas que se estan usando*/
void GraficaEditor::cambiarAInexistente(){  tipoDeCultivo=0;}
void GraficaEditor::cambiarASinPlantar(){  tipoDeCultivo=1;}
void GraficaEditor::cambiarAmaiz(){ tipoDeCultivo=2; }
void GraficaEditor::cambiarAGirasol(){  tipoDeCultivo=3;}
void GraficaEditor::cambiarAsoja(){  tipoDeCultivo=4; }

void  GraficaEditor::abrirArchivo(){
	
    fileSelector=gtk_file_selection_new( "Abrir achivo" );
	gtk_signal_connect (GTK_OBJECT (fileSelector), "destroy", (GtkSignalFunc) gtk_widget_destroy,
			       GTK_OBJECT (fileSelector));
    /* Conectar el ok_button con la función file_ok_sel*/ 
    gtk_signal_connect (GTK_OBJECT (GTK_FILE_SELECTION (fileSelector)->ok_button),
			"clicked", (GtkSignalFunc) file_ok_boton_Abrir, this );
    
    /* Conectar el cancel_button con la destrucción del widget */
    gtk_signal_connect_object (GTK_OBJECT (GTK_FILE_SELECTION (fileSelector)->cancel_button),
			       "clicked", (GtkSignalFunc) gtk_widget_destroy,
			       GTK_OBJECT (fileSelector));
	
	gtk_widget_show(fileSelector);
}

void  GraficaEditor::guardarArchivo(){
	
    fileSelector=gtk_file_selection_new( "Guardar achivo" );
	gtk_signal_connect (GTK_OBJECT (fileSelector), "destroy", (GtkSignalFunc) gtk_widget_destroy,
			       GTK_OBJECT (fileSelector));
    /* Conectar el ok_button con la función file_ok_sel*/ 
    gtk_signal_connect (GTK_OBJECT (GTK_FILE_SELECTION (fileSelector)->ok_button),
			"clicked", (GtkSignalFunc) file_ok_boton_Guardar, this );
    
    /* Conectar el cancel_button con la destrucción del widget */
    gtk_signal_connect_object (GTK_OBJECT (GTK_FILE_SELECTION (fileSelector)->cancel_button),
			       "clicked", (GtkSignalFunc) gtk_widget_destroy,
			       GTK_OBJECT (fileSelector));
	
	gtk_widget_show(fileSelector);
}


void GraficaEditor::abrir(){
	  Campo c;
	  c.cargarCampo( gtk_file_selection_get_filename (GTK_FILE_SELECTION (fileSelector)),campo);
	 g_print ("Abrir Archivo : %s\n", gtk_file_selection_get_filename (GTK_FILE_SELECTION (fileSelector)));
	 gtk_widget_destroy(fileSelector);
	
	seGuardoCambios=false;
	GdkRectangle update_rect;
	update_rect.x = 0;
    update_rect.y = 0;
    update_rect.width = 20*32;
    update_rect.height = 15*32;
	dibujaCampo(drawing_area);
	gtk_widget_draw (drawing_area, &update_rect);
}

void GraficaEditor::guardar(){
	 Campo c;
	 c.guardarCampo( gtk_file_selection_get_filename (GTK_FILE_SELECTION (fileSelector)),campo);
	 seGuardoCambios=true;
	 g_print ("Guardar Archivo : %s\n", gtk_file_selection_get_filename (GTK_FILE_SELECTION (fileSelector)));
	 gtk_widget_destroy(fileSelector);
	  
	 if(ventana!=NULL) {
		 			gtk_widget_destroy(ventana);
		 			gtk_main_quit();
	 }	 
}


void GraficaEditor::cerrarVentana (GtkWidget *widget){
        
	     /* GtkWidget *ventana;*/
		 ventana = gtk_dialog_new ();
		 GtkWidget *etiqueta = gtk_label_new ("Desea guardar los cambios");
		 gtk_box_pack_start (GTK_BOX (GTK_DIALOG (ventana)->vbox), etiqueta, TRUE, TRUE, 0);
	
         GtkWidget *boton = gtk_button_new_with_label ("Si");
   		 gtk_box_pack_start (GTK_BOX (GTK_DIALOG (ventana)->vbox), boton, TRUE, TRUE, 0);
  		 /*Accion del boton al clickear*/
    	 gtk_signal_connect (GTK_OBJECT (boton), "clicked", (GtkSignalFunc) (apretarBotonGuardar),this);		 
	 	 boton = gtk_button_new_with_label ("No");
   		 gtk_box_pack_start (GTK_BOX (GTK_DIALOG (ventana)->vbox), boton, TRUE, TRUE, 0);
   		/*Accion del boton al clickear*/
         gtk_signal_connect (GTK_OBJECT (boton), "clicked", (GtkSignalFunc) (gtk_main_quit),this);		 
	   
	   if(seGuardoCambios==false){
        	gtk_widget_show_all(ventana);
	   }
 		else 	
            gtk_main_quit();			
}
